package com.itheima.mybatis.controller;

import com.itheima.mybatis.mapper.UserMapper;
import com.itheima.mybatis.pojo.table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/api")
public class DataController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/insert")
    public Map<String, String> insertData(@RequestBody Map<String, String> requestData) throws SQLException {
        table  t= new table();
        t.setItem_name(requestData.get("item_name"));
        t.setValue(requestData.get("value"));
        userMapper.insert(t);
        Map<String, String> response = new HashMap<>();
        response.put("message", "Data inserted successfully");
        return response;
    }

    @GetMapping("/data")
//    public List<Map<String, String>> fetchData() {
    public  List<table> fetchData() {
        return userMapper.selectAllTable();
    }

//
    @PutMapping("/update/{id}")
    public Map<String, String> updateData(@PathVariable int id, @RequestBody Map<String, String> requestData)  {
        table  t= new table();
        t.setItem_name(requestData.get("item_name"));
        t.setValue(requestData.get("value"));
        t.setId(id);
        userMapper.update(t);
        Map<String, String> response = new HashMap<>();
        response.put("message", "Data updated successfully");
        return response;
    }
//


    @DeleteMapping("/delete/{id}")
    public Map<String, String> deleteData(@PathVariable int id)  {
        userMapper.delete(id);
        Map<String, String> response = new HashMap<>();
        response.put("message", "Data deleted successfully");
        return response;
    }
}
